﻿Imports System.Data.SqlClient

Public Class DbConnectionHelper
    ' 连接字符串（请按实际修改）
    Private Shared ReadOnly connectionString As String = "Data Source=localhost\LUODENG;Initial Catalog=WDSH;User ID=sa;Password=2002"

    Public Shared Function GetConnectString() As String
        Return connectionString
    End Function


    ' 公共连接对象
    Public Shared ReadOnly Property Connection As SqlConnection
        Get
            ' 每次获取新的连接实例
            Return New SqlConnection(connectionString)
        End Get
    End Property

    ' 打开连接
    Public Shared Sub OpenConnection(conn As SqlConnection)
        If conn IsNot Nothing AndAlso conn.State = ConnectionState.Closed Then
            conn.Open()
        End If
    End Sub

    ' 关闭连接
    Public Shared Sub CloseConnection(conn As SqlConnection)
        If conn IsNot Nothing AndAlso conn.State <> ConnectionState.Closed Then
            conn.Close()
        End If
    End Sub

    '====================================
    ' 🔹 测试数据库连接是否正常
    '====================================
    Public Shared Function TestConnection() As Boolean
        Try
            Using conn As New SqlConnection(connectionString)
                conn.Open()
                Return True   ' 连接成功
            End Using
        Catch ex As Exception
            MessageBox.Show("数据库连接失败！" & vbCrLf & ex.Message, "连接测试", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return False
        End Try
    End Function
    '====================================
    ' 🔹 执行查询语句，并绑定到 DataGridView
    '====================================
    Public Shared Sub FillDataGridView(dgv As DataGridView, sql As String)
        Try
            Using conn As New SqlConnection(connectionString)
                Using da As New SqlDataAdapter(sql, conn)
                    Dim dt As New DataTable()
                    da.Fill(dt)
                    dgv.DataSource = dt
                End Using
            End Using
        Catch ex As Exception
            MessageBox.Show("执行查询时出错！" & vbCrLf & ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
End Class
